// 导入验证插件
import wxValidate from 'wechat-validate'
Page({
  behaviors: [wxValidate],
  data: {
    name: '',
    mobile: '',
    gender: 1,
    houseId: '',
    visitDate: '',
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    currentDate: Date.now(),
    maxDate: Date.now() + 1000 * 3600 * 24 * 3
  },
  // 表单校验规则
  rules: {
    houseId: [
      {required: true, message: '请选择房屋信息'}
    ],
    name: [
      {required: true, message: '请输入访客姓名'},
      {pattern: /[\u4e00-\u9fa5]{2,5}/, message: '请输入正确的名字'}
    ],
    mobile: [
      {required: true, message: '请输入访客手机号码'},
      {pattern: /^1[3-8]\d{9}$/, message: '请输入正确的手机号码'}
    ],
    visitDate: [
      {required: true, message: '请输入访问日期'},
    ]
  },
  onLoad() {
    // 调用房屋列表函数
    this.getHouseList()
  },

  // 获取房屋列表
  async getHouseList() {
    // 调用接口
    const {code, data: houseList} = await wx.http.get('/house')
    // 检测接口调用是否成功
    if(code !== 10000) return wx.utils.toast()
    // 渲染数据
    this.setData({houseList})
  },
  // 监听select事件，获取用户选择的房屋
  selectHouseInfo(ev) {
    // console.log(ev)
    // 记录房屋信息
    this.setData({
      houseId: ev.detail.id,
      houseInfo: ev.detail.name
    })
  },

  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  
  // h获取用户选择的访问日期
  selectDateInfo(ev) {
    // console.log(ev)
    this.setData({
      visitDate: wx.utils.dateFormat(ev.detail),
      dateLayerVisible: false
    })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  // 提交表单验证
  async goPassport() {
    // 验证表单数据
    if(!this.validate()) return
    //  获取接口需要的参数
    const {name, mobile, gender, houseId, visitDate} = this.data
    // 调用接口
    const {code, data: {id}} = await wx.http.post('/visitor',{
      name, mobile, gender, houseId, visitDate
    })
    // 检测是否调用成功
    if(code !== 10000) return wx.utils.toast()
    // 跳转页面
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + id,
    })
  },
})
